package com.aliyun.messagemgt.application.service.Impl.push.dingding.dingtalk;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.messagemgt.util.redis.Redis;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *@Author Znight
 *@Date 17:30 2019/7/23
 */
public class DingTalkTokenUtil {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkTokenUtil.class);

    private static final String KEY = "dingTalkToken";

    private static final String TOKEN_URL = "https://oapi.dingtalk.com/gettoken";

    public static String getToken(String appKey, String appSecret){
       String token = Redis.getValue(KEY + appSecret);
       // 如果redis中获取不到则重新获取
        if (token == null) {
            logger.info("redis 中没有{} 的token信息，重新获取", appKey);
            token = updateDingTalkToken(appKey,appSecret);
        }
        logger.info(" access_token {} ",token);
        return token;
    }

    public static String updateDingTalkToken(String appKey, String appSecret){
        String accessToken = null;
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(TOKEN_URL);
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            accessToken = JSONObject.parseObject(response.getBody()).getString("access_token");
            Redis.setXX(KEY+appSecret,accessToken,60*60*2);
        }catch (Exception e){
            logger.error(" 获取钉钉token时出现错误 {} ",e.toString());
        }
        return accessToken;
    }
}
